package com.lqzs.businessmanager.http

import android.content.Context
import android.text.TextUtils
import android.util.Log
import com.lqzs.businessmanager.BusinessManagerApplication
import com.lqzs.businessmanager.Config
import com.lqzs.businessmanager.Config.Companion.BUSINESS_PLATFORM_ID
import com.lqzs.businessmanager.Config.Companion.BUSINESS_SHOP_ID
import com.lqzs.businessmanager.base.HttpResult
import com.lqzs.businessmanager.bean.AccessInfo
import com.lqzs.businessmanager.bean.EleInfo
import com.lqzs.businessmanager.bean.MerChantInfo
import com.lqzs.businessmanager.bean.request.AddReviewInfoRequest
import com.lqzs.businessmanager.bean.request.EleAddReviewRequest
import com.lqzs.businessmanager.bean.request.GetUnReplyReviewsRequest
import com.lqzs.businessmanager.bean.request.LatestReViewRequest
import com.lqzs.businessmanager.bean.request.LoginShopRequest
import com.lqzs.businessmanager.bean.request.UpdateOrderInfo
import com.lqzs.businessmanager.bean.request.UpdateReviewStateRequest
import com.lqzs.businessmanager.bean.response.GetUnReplyReviewsResponse
import com.lqzs.businessmanager.bean.response.LatestReViewResponse
import com.lqzs.businessmanager.bean.response.LoginShopResponse
import com.lqzs.businessmanager.bean.response.PlatfromResponse
import com.lqzs.businessmanager.bean.response.ReviewInfoResponse
import com.lqzs.businessmanager.bean.response.ReviewStateResponse
import com.lqzs.businessmanager.bean.response.VenDorResponse
import com.lqzs.businessmanager.http.LogInterceptor.Companion.TAG
import com.lqzs.businessmanager.utils.PreferencesUtil
import retrofit2.HttpException
import retrofit2.Response
import java.io.EOFException
import java.io.IOException
import java.net.ConnectException
import java.net.SocketException
import java.net.SocketTimeoutException
import java.net.UnknownHostException


/**
 * 获取所有商家信息
 */
suspend fun requestVenDorList(): Response<HttpResult<List<VenDorResponse>>>? {
    try {
        return HttpUtils.getInstance().create().getVenDorList()
    }catch (e :Exception){
        Log.e(TAG, handleException(e))
        return null
    }
}

/**
 * 获取所有评论信息
 */
suspend fun requestPlatformList(): Response<HttpResult<List<PlatfromResponse>>>? {
    try {
        return HttpUtils.getInstance().create().getPlatfromList()
    }catch (e :Exception){
        Log.e(TAG, handleException(e))
        return null
    }
}

/**
 * 填充数据
 */
suspend fun addMerChantInfo(merChantInfo : MerChantInfo): Response<HttpResult<ReviewInfoResponse>>? {
    try {
        if (merChantInfo.upload == 1 || merChantInfo.upload == 3) {
            return null
        }

        val accessInfo = AccessInfo()
        val request = AddReviewInfoRequest(accessInfo)

        request.order_infos =
            if (TextUtils.isEmpty(merChantInfo.orderDetails)) "" else "订单详情：${merChantInfo.orderDetails}"
        request.reviewer_infos =
            "${merChantInfo.userName}\n${merChantInfo.fraction}\n${merChantInfo.chaseCommentsTime}\n${merChantInfo.chaseComments}"
        request.reply_infos = merChantInfo.merchantReplied
        request.append_infos = merChantInfo.reviewFollow
        val vendorInfo = BusinessManagerApplication.getVendorInfo()
        vendorInfo?.let {
            request.platform_name = vendorInfo.platform_name
            request.branch_name = vendorInfo.address
            request.branch_id = vendorInfo.branch_id
        }

        return HttpUtils.getInstance().create().addReviewInfo(request)
    } catch (e: Exception) {
        Log.e(TAG, handleException(e))
        return null
    }
}

/**
 * 填充数据
 */
suspend fun addReviewInfo(context: Context,accessInfo : EleInfo): Response<HttpResult<ReviewInfoResponse>>? {
    if (accessInfo.upload == 1 ||accessInfo.upload == 3){
        return null
    }
    val request = EleAddReviewRequest(accessInfo)
    request.branch_id = PreferencesUtil.getString(context,BUSINESS_SHOP_ID)

    try {
        return HttpUtils.getInstance().create().addReviewNaposInfo(request)
    }catch (e :Exception){
        Log.e(TAG, handleException(e))
        return null
    }
}

/**
 * 填充数据
 */
suspend fun addReviewInfo(accessInfo : AccessInfo): Response<HttpResult<ReviewInfoResponse>>? {
    if (accessInfo.upload == 1 ||accessInfo.upload == 3){
        return null
    }
    val request = AddReviewInfoRequest(accessInfo)
    val reviewerInfos = request.reviewer_infos
    reviewerInfos?.let {
        if (it.contains("拼好饭")) {
            return null
        }
    }


    val vendorInfo = BusinessManagerApplication.getVendorInfo()
    vendorInfo?.let {
        request.platform_name = vendorInfo.platform_name
        request.branch_name = vendorInfo.address
        request.branch_id = vendorInfo.branch_id
    }

    try {
        return HttpUtils.getInstance().create().addReviewInfo(request)
    }catch (e :Exception){
        Log.e(TAG, handleException(e))
        return null
    }
}

/*suspend fun updateReviewInfo(context: Context,accessInfo : AccessInfo): Response<HttpResult<ReviewInfoResponse>>? {
    val request = AddReviewInfoRequest(accessInfo)
    request.branch_id = PreferencesUtil.getString(context,BUSINESS_SHOP_ID)
    try {
        return HttpUtils.getInstance().create().updateReviewInfo(request)
    }catch (e :Exception){
        Log.e(TAG, handleException(e))
        return null
    }
}*/

/**
 * 绑定商户
 */
suspend fun loginShop(context: Context,shopPhone:String): Response<HttpResult<List<LoginShopResponse>>>?{

    val request = LoginShopRequest()
    //手机号
    request.phone = shopPhone
    try {
        return HttpUtils.getInstance().create().loginShop(request)
    }catch (e :Exception){
        Log.e(TAG, handleException(e))
        return null
    }
}

/**
 * 获取最新评论信息
 */
suspend fun getLatestReView(mContext: Context):Response<HttpResult<LatestReViewResponse>>?{

    val request = LatestReViewRequest()
    //分店
    request.branch_id = PreferencesUtil.getString(mContext,BUSINESS_SHOP_ID)
    request.platform_id = PreferencesUtil.getString(mContext,BUSINESS_PLATFORM_ID)
    try {
        return HttpUtils.getInstance().create().getLatestReView(request)
    }catch (e :Exception){
        Log.e(TAG, handleException(e))
        return null
    }
}

/**
 * 更新评论状态
 */
suspend fun updateReviewState(reviewId:String) : Response<HttpResult<ReviewStateResponse>>? {

    val request = UpdateReviewStateRequest()
    //评论ID
    request.review_id = reviewId
    val vendorInfo = BusinessManagerApplication.getVendorInfo()
    vendorInfo?.let {
        request.platform_id = it.platform_id
    }
    //评论状态
    request.state = 2
    Log.e("LYF", "updateReviewState: reviewId: ${request.review_id} , platformId: ${request.platform_id} , state: ${request.state}")
    try {
        return HttpUtils.getInstance().create().updateReviewState(request)
    }catch (e :Exception){
        Log.e(TAG, handleException(e))
        return null
    }
}

/**
 * 更新订单状态
 */
suspend fun updateOrderInfo(context: Context,accessInfo : AccessInfo): Response<HttpResult<ReviewStateResponse>>? {
    if (accessInfo.upload != 3)
        return null

    val request = UpdateOrderInfo()
    request.platform_id = PreferencesUtil.getString(context,Config.BUSINESS_PLATFORM_ID)
    request.order_infos = accessInfo.orderDetails
    request.review_id = accessInfo.reviewId
    try {
        return HttpUtils.getInstance().create().updateOrderInfo(request)
    }catch (e :Exception){
        Log.e(TAG, handleException(e))
        return null
    }
}

suspend fun updateOrderInfo(context: Context,accessInfo : EleInfo): Response<HttpResult<ReviewStateResponse>>? {
    if (accessInfo.upload != 3)
        return null

    val request = UpdateOrderInfo()
    request.platform_id = PreferencesUtil.getString(context,Config.BUSINESS_PLATFORM_ID)
    request.order_infos = "更新订单状态----------------------------------------------"
    request.review_id = accessInfo.reviewId
    try {
        return HttpUtils.getInstance().create().updateOrderInfo(request)
    }catch (e :Exception){
        Log.e(TAG, handleException(e))
        return null
    }
}

fun <T> makeRequest(response: Response<HttpResult<T>>?): T? {
    return response?.takeIf { it.isSuccessful }?.body()?.takeIf { it.code == 1000 }?.data
}

/**
 * 绑定商户
 */
suspend fun getUnReplyReviews(branchId:Int?): Response<HttpResult<List<GetUnReplyReviewsResponse>>>?{

    val request = GetUnReplyReviewsRequest()
    //手机号
    request.branch_id = branchId
    try {
        return HttpUtils.getInstance().create().getUnReplyReviews(request)
    }catch (e :Exception){
        Log.e(TAG, handleException(e))
        return null
    }
}

/**
 * 异常处理
 */
fun handleException(e: Throwable) = when(e){
    is IOException -> "网络错误，请检查您的网络连接"
    is HttpException -> "服务端错误"
    is SocketException -> "链接错误"
    is SocketTimeoutException -> "Socket连接超时异常"
    is UnknownHostException -> "UnknownHostException"
    is ConnectException -> "ConnectException"
    is EOFException -> "EOFException"
    else -> "未知错误"
}